<template>
  <div class="appointment-management">
    <div class="page-header">
      <h1 class="page-title">预约管理</h1>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="showAddDialog = true">
          新增预约
        </el-button>
        <!-- <el-button :icon="Calendar" @click="showCalendarView = !showCalendarView">
          {{ showCalendarView ? '列表视图' : '日历视图' }}
        </el-button> -->
        <el-button :icon="Download" @click="exportAppointments">
          导出数据
        </el-button>
      </div>
    </div>


    <!-- 搜索和筛选 (保留原有功能) -->
    <el-card class="search-card" shadow="never" style="margin-top: 16px;">
      <template #header>
        <div class="card-header">
          <span>预约查询</span>
          <el-button type="primary" size="small" @click="handleRefresh" :loading="loading">
            刷新数据
          </el-button>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="本地搜索患者姓名"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterStatus" placeholder="预约状态" clearable @change="handleFilter">
            <el-option label="已预约" value="1" />
            <el-option label="排队中" value="3" />
            <el-option label="已完成" value="4" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterPeriod" placeholder="就诊时段" clearable @change="handleFilter">
            <el-option label="全部" value="全部" />
            <el-option label="上午" value="上午" />
            <el-option label="下午" value="下午" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-date-picker
            v-model="filterDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            @change="handleFilter"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="6">
          <div class="stats-info">
            <!-- <span class="stat-item">今日预约: <strong>{{ appointmentStats.todayAppointments }}</strong></span>
            <span class="stat-item">总数据: <strong>{{ appointmentStore.totalCount }}</strong></span> -->
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 日历视图 -->
    <el-card v-if="showCalendarView" shadow="never" class="calendar-card">
      <template #header>
        <div class="card-header">
          <span>预约日历</span>
          <el-date-picker
            v-model="calendarDate"
            type="month"
            placeholder="选择月份"
            @change="handleCalendarChange"
          />
        </div>
      </template>
      <el-calendar v-model="calendarDate" :range="calendarRange">
        <template #date-cell="{ data }">
          <div class="calendar-cell">
            <div class="date">{{ data.day.split('-').slice(-1)[0] }}</div>
            <div class="appointments-count" v-if="getDateAppointments(data.day).length > 0">
              <el-tag size="small" type="primary">
                {{ getDateAppointments(data.day).length }}个预约
              </el-tag>
            </div>
          </div>
        </template>
      </el-calendar>
    </el-card>

    <!-- 列表视图 -->
    <template v-else>
      <el-row :gutter="16" class="list-and-queue">
        <el-col :span="16">
          <el-card shadow="never">
            <el-table
              :data="displayedAppointments"
              v-loading="loading"
              stripe
              @selection-change="handleSelectionChange"
              @row-click="handleRowClick"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="预约编号" width="100" show-overflow-tooltip />
              <el-table-column prop="patientName" label="患者姓名" width="100">
                <template #default="{ row }">
                  <el-button type="text" @click="handleViewDetail(row)">
                    {{ row.patientName }}
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column prop="period" label="就诊时段" width="100" />
              <el-table-column prop="slotNo" label="号码" width="80" />
              <el-table-column prop="bookedAt" label="就诊时间" width="160" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStatusColor(row.status)" size="small">
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <!-- <el-table-column label="操作" width="150" fixed="right">
                <template #default="{ row }">
                  <el-button type="text" size="small" @click="handleViewDetail(row)">查看详情</el-button>
                  <el-button type="text" size="small" @click="handleRefresh">刷新</el-button>
                </template>
              </el-table-column> -->
            </el-table>

            <div class="pagination-wrapper">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 50]"
                :total="appointmentStore.totalCount"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-col>

        <!-- 右侧叫号等待队列 -->
        <el-col :span="8">
          <el-card shadow="never" class="queue-card">
            <template #header>
              <div class="card-header">
                <span>叫号等待队列</span>
                <div class="queue-controls">
                  <!-- 新增：时段切换按钮组 -->
                  <el-radio-group 
                    v-model="selectedPeriod" 
                    size="small" 
                    @change="handlePeriodChange"
                    style="margin-right: 10px;"
                  >
                    <el-radio-button label="上午">上午</el-radio-button>
                    <el-radio-button label="下午">下午</el-radio-button>
                  </el-radio-group>
                  <el-button size="small" type="primary" @click="handleQueueRefresh" :loading="loading || appointmentStore.queueLoading">刷新</el-button>
                </div>
              </div>
            </template>

            <div v-if="currentCalling" class="current-calling">
              <div class="calling-info">
                <el-tag type="success" effect="dark">{{ currentCalling.slotNo || currentCalling.queueNumber }}号</el-tag>
                <span class="name">{{ currentCalling.patientName }}</span>
                <span class="time">{{ currentCalling.bookedAt }}</span>
              </div>
              <div class="calling-actions">
                <el-button size="small" type="primary" @click="handleComplete(currentCalling)">完成</el-button>
                <el-button size="small" @click="currentCalling = null">结束</el-button>
              </div>
            </div>

            <!-- 显示从API获取的队列数据 -->
            <el-empty v-if="appointmentStore.queueList.length === 0 && !appointmentStore.queueLoading" description="暂无待叫号" />
            <el-scrollbar v-else-if="appointmentStore.queueList.length > 0" height="480">
              <div
                v-for="item in appointmentStore.queueList"
                :key="item.id"
                class="queue-item"
                :class="{ 'calling': callingStates[item.id] }"
              >
                <div class="left">
                  <el-tag type="primary">{{ item.slotNo }}号</el-tag>
                </div>
                
                <!-- 显示倒计时状态（如果正在叫号） -->
                <div class="middle">
                  <div v-if="callingStates[item.id]" class="calling-status">
                    <el-tag type="warning" effect="dark" class="countdown-tag">
                      <el-icon><Timer /></el-icon>
                      {{ callingTimers[item.id] }}s
                    </el-tag>
                    <span class="calling-text">叫号中</span>
                  </div>
                  <div v-else class="waiting-status">
                    <span class="waiting-text">等待叫号</span>
                  </div>
                </div>
                
                <!-- 按钮区域 - 叫号和完成独立 -->
                <div class="right">
                  <!-- 叫号按钮 - 始终显示 -->
                  <el-button 
                    size="small" 
                    type="primary" 
                    @click="handleCallSlot(item)"
                    :disabled="callingStates[item.id]"
                  >
                    {{ callingStates[item.id] ? '叫号中' : '叫号' }}
                  </el-button>
                  
                  <!-- 完成按钮 - 始终显示，独立于叫号状态 -->
                  <el-button 
                    size="small" 
                    type="success" 
                    @click="handleCompleteAppointment(item)"
                  >
                    完成
                  </el-button>
                </div>
              </div>
            </el-scrollbar>
            
            <!-- 加载状态 -->
            <div v-if="appointmentStore.queueLoading" style="text-align: center; padding: 20px;">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span style="margin-left: 8px;">加载中...</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </template>

    <!-- 新增/编辑预约对话框 -->
    <!-- <el-dialog
      v-model="showAddDialog"
      :title="editingAppointment ? '编辑预约' : '新增预约'"
      width="700px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="appointmentForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="患者" prop="patientId">
              <el-select
                v-model="appointmentForm.patientId"
                placeholder="请选择患者"
                filterable
                @change="handlePatientChange"
              >
                <el-option 
                  v-for="patient in patientOptions" 
                  :key="patient.id"
                  :label="`${patient.name} (${patient.phone})`"
                  :value="patient.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医生" prop="doctorId">
              <el-select
                v-model="appointmentForm.doctorId"
                placeholder="请选择医生"
                filterable
                @change="handleDoctorChange"
              >
                <el-option 
                  v-for="doctor in doctorOptions" 
                  :key="doctor.id"
                  :label="`${doctor.name} (${doctor.department})`"
                  :value="doctor.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预约日期" prop="appointmentDate">
              <el-date-picker
                v-model="appointmentForm.appointmentDate"
                type="date"
                placeholder="选择日期"
                :disabled-date="disabledDate"
                @change="handleDateChange"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约时间" prop="appointmentTime">
              <el-select
                v-model="appointmentForm.appointmentTime"
                placeholder="请选择时间"
                :disabled="!appointmentForm.doctorId || !appointmentForm.appointmentDate"
              >
                <el-option 
                  v-for="slot in availableTimeSlots" 
                  :key="slot"
                  :label="slot"
                  :value="slot"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预约类型" prop="type">
              <el-select v-model="appointmentForm.type" placeholder="请选择类型">
                <el-option label="初诊" value="初诊" />
                <el-option label="复诊" value="复诊" />
                <el-option label="急诊" value="急诊" />
                <el-option label="体检" value="体检" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="appointmentForm.priority" placeholder="请选择优先级">
                <el-option label="普通" value="普通" />
                <el-option label="紧急" value="紧急" />
                <el-option label="加急" value="加急" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="就诊原因" prop="reason">
          <el-input v-model="appointmentForm.reason" placeholder="请输入就诊原因" />
        </el-form-item>

        <el-form-item label="症状描述">
          <el-input 
            v-model="appointmentForm.symptoms" 
            type="textarea" 
            :rows="3"
            placeholder="请描述主要症状"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预约费用" prop="fee">
              <el-input-number 
                v-model="appointmentForm.fee" 
                :min="0" 
                :precision="2"
                placeholder="费用"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付状态" prop="paymentStatus">
              <el-select v-model="appointmentForm.paymentStatus" placeholder="支付状态">
                <el-option label="未支付" value="未支付" />
                <el-option label="已支付" value="已支付" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input 
            v-model="appointmentForm.notes" 
            type="textarea" 
            :rows="2"
            placeholder="其他备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="loading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog> -->

    <!-- 预约详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="预约详情"
      width="800px"
    >
      <div v-if="currentAppointment" class="appointment-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预约编号">{{ currentAppointment.id }}</el-descriptions-item>
          <el-descriptions-item label="预约状态">
            <el-tag :type="getStatusColor(currentAppointment.status)">
              {{ currentAppointment.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="患者姓名">{{ currentAppointment.patientName }}</el-descriptions-item>
          <el-descriptions-item label="医生姓名">{{ currentAppointment.doctorName }}</el-descriptions-item>
          <el-descriptions-item label="科室">{{ currentAppointment.department }}</el-descriptions-item>
          <el-descriptions-item label="预约类型">
            <el-tag :type="getTypeColor(currentAppointment.type)">
              {{ currentAppointment.type }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预约日期">{{ currentAppointment.appointmentDate }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ currentAppointment.appointmentTime }}</el-descriptions-item>
          <el-descriptions-item label="排队号">{{ currentAppointment.queueNumber }}</el-descriptions-item>
          <el-descriptions-item label="预计就诊时间">{{ currentAppointment.estimatedTime }}</el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityColor(currentAppointment.priority)">
              {{ currentAppointment.priority }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="费用">¥{{ currentAppointment.fee }}</el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getPaymentColor(currentAppointment.paymentStatus)">
              {{ currentAppointment.paymentStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="提醒状态">
            <el-tag :type="currentAppointment.reminderSent ? 'success' : 'info'">
              {{ currentAppointment.reminderSent ? '已发送' : '未发送' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="就诊原因" :span="2">{{ currentAppointment.reason }}</el-descriptions-item>
          <el-descriptions-item label="症状描述" :span="2">{{ currentAppointment.symptoms }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentAppointment.notes }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(currentAppointment.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(currentAppointment.updatedAt) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Search, Calendar, Loading, Timer } from '@element-plus/icons-vue'
import { useAppointmentStore, type Appointment } from '@/stores/modules/appointment'
import { usePatientStore } from '@/stores/modules/patient'
import { useDoctorStore } from '@/stores/modules/doctor'
import { useUserStore } from '@/stores/modules/user'
import {
  getPatientAppointments,
  getCurrentClinicStaff,
  getQueue,
  updatePatientAppStatus,
  callSlot,
  convertToChineseTime,
  formatAppointmentStatus,
  formatBookedAt,
  type AppointmentQueryParams,
  type AppointmentInfo,
  type DoctorClinicInfo,
  type QueueItem,
  type UpdateAppointmentStatusRequest
} from '@/api/appointment/appapi'

const appointmentStore = useAppointmentStore()
const patientStore = usePatientStore()
const doctorStore = useDoctorStore()
const userStore = useUserStore()

// 响应式数据
const searchQuery = ref('')
const filterStatus = ref('')
const filterPeriod = ref('')
const filterDate = ref('')
const currentPage = ref(1)
const pageSize = ref(5)
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const showCalendarView = ref(false)
const calendarDate = ref(new Date())
const editingAppointment = ref<Appointment | null>(null)
const selectedAppointments = ref<Appointment[]>([])
const loading = ref(false)

// 叫号相关状态
const callingTimers = ref<Record<string, number>>({}) // 存储每个预约的倒计时
const callingStates = ref<Record<string, boolean>>({}) // 存储每个预约的叫号状态

// 新增：队列时段选择状态
const selectedPeriod = ref<'上午' | '下午'>('上午')

// 初始化默认时段（可以根据当前时间设置，或者默认为上午）
const initDefaultPeriod = () => {
  const now = new Date()
  const hours = now.getHours()
  selectedPeriod.value = hours < 13 ? '上午' : '下午'
}

// 新增：时段切换处理方法
const handlePeriodChange = async (period: '上午' | '下午') => {
  selectedPeriod.value = period
  await handleQueueRefresh()
}

// API查询表单
const queryForm = ref({
  patientName: '',
  period: '',
  status: null as number | null,
  bookedAt: ''
})

// 表单相关
const formRef = ref()
const appointmentForm = ref({
  patientId: '',
  patientName: '',
  doctorId: '',
  doctorName: '',
  department: '',
  appointmentDate: '',
  appointmentTime: '',
  type: '初诊' as Appointment['type'],
  reason: '',
  symptoms: '',
  priority: '普通' as Appointment['priority'],
  fee: 50,
  paymentStatus: '未支付' as Appointment['paymentStatus'],
  notes: ''
})

// 表单验证规则
const formRules = {
  patientId: [
    { required: true, message: '请选择患者', trigger: 'change' }
  ],
  doctorId: [
    { required: true, message: '请选择医生', trigger: 'change' }
  ],
  appointmentDate: [
    { required: true, message: '请选择预约日期', trigger: 'change' }
  ],
  appointmentTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择预约类型', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入就诊原因', trigger: 'blur' }
  ]
}

// 计算属性
// 修改计算属性，移除本地分页逻辑
const displayedAppointments = computed(() => {
  // 如果有API数据，直接返回API数据（已经是分页后的）
  if (appointmentStore.apiAppointments && appointmentStore.apiAppointments.length > 0) {
    // 将API数据转换为本地格式用于显示
    return appointmentStore.apiAppointments.map(item => ({
      id: item.id,
      patientId: item.patientId,
      patientName: item.patientName,
      period: item.period,
      slotNo: item.slotNo,
      bookedAt: item.bookedAt,
      status: item.status === 1 ? '已预约' : item.status === 3 ? '排队中' : '已完成',
      // 添加其他必要的字段以保持兼容性
      appointmentDate: item.bookedAt.split(' ')[0],
      appointmentTime: item.period === '上午' ? '09:00' : '14:00',
      type: '初诊',
      reason: '',
      priority: '普通',
      fee: 0,
      paymentStatus: '未支付',
      notes: item.cancelReason || '',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      queueNumber: item.slotNo,
      estimatedTime: '',
      reminderSent: false,
      cancelReason: item.cancelReason
    }))
  }
  
  // 如果没有API数据，使用本地数据并进行筛选和分页
  let result = appointmentStore.appointments

  if (searchQuery.value) {
    result = appointmentStore.searchAppointments(searchQuery.value)
  }

  if (filterStatus.value) {
    const statusText = filterStatus.value === '1' ? '已预约' : filterStatus.value === '2' ? '已取消' : filterStatus.value
    result = result.filter(a => a.status === statusText)
  }

  if (filterPeriod.value) {
    result = result.filter(a => a.period === filterPeriod.value)
  }

  if (filterDate.value) {
    result = result.filter(a => a.appointmentDate === filterDate.value)
  }

  // 本地分页（仅在使用本地数据时）
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

const currentAppointment = computed(() => appointmentStore.currentAppointment)
const appointmentStats = computed(() => appointmentStore.getAppointmentStats())

const patientOptions = computed(() => patientStore.patients)
const doctorOptions = computed(() => doctorStore.doctors.filter(d => d.status === '在职'))

const availableTimeSlots = computed(() => {
  if (!appointmentForm.value.doctorId || !appointmentForm.value.appointmentDate) {
    return []
  }
  return appointmentStore.getDoctorAvailableSlots(
    appointmentForm.value.doctorId, 
    appointmentForm.value.appointmentDate
  )
})

const calendarRange = computed(() => {
  const start = new Date(calendarDate.value.getFullYear(), calendarDate.value.getMonth(), 1)
  const end = new Date(calendarDate.value.getFullYear(), calendarDate.value.getMonth() + 1, 0)
  return [start, end]
})

// 队列取号工具
const getQueueNo = (a: any) => (a?.slotNo ?? a?.queueNumber ?? 0)

// 待叫号队列：仅显示“已预约/已确认”，并按号排序；受左侧筛选影响
const waitingQueue = computed(() => {
  const list = appointmentStore.appointments
  console.log("11",list)
  return list
    .filter(a =>
      (a.status === '已预约' || a.status === '已确认') &&
      (!filterDate.value || a.appointmentDate === filterDate.value) &&
      (!filterPeriod.value || a.period === filterPeriod.value)
    )
    .sort((a, b) => getQueueNo(a) - getQueueNo(b))
})

const currentCalling = ref<Appointment | null>(null)

const callAppointment = async (item: Appointment) => {
  console.log(item)
  currentCalling.value = item
  // 可选：标记为“已确认”，便于与未叫号区分
  try { await appointmentStore.confirmAppointment(item.id) } catch {}
}

// 叫号功能 - 独立操作，不影响完成
const handleCallSlot = async (item: QueueItem) => {
  try {
    console.log('叫号:', item)
    
    // 发送叫号请求
    await appointmentStore.callSlotApi(item.id)
    ElMessage.success('叫号成功')
    
    // 设置叫号状态
    callingStates.value[item.id] = true
    
    // 开始60秒倒计时
    startCountdown(item.id)
    
  } catch (error) {
    console.error('叫号失败:', error)
    ElMessage.error('叫号失败')
  }
}

// 开始倒计时 - 只是提醒，不影响完成功能
const startCountdown = (appointmentId: string) => {
  callingTimers.value[appointmentId] = 60
  
  const timer = setInterval(() => {
    if (callingTimers.value[appointmentId] > 0) {
      callingTimers.value[appointmentId]--
    } else {
      // 倒计时结束，只清除叫号状态，不影响完成功能
      clearInterval(timer)
      callingStates.value[appointmentId] = false
      delete callingTimers.value[appointmentId]
      ElMessage.info('叫号倒计时结束')
    }
  }, 1000)
}

// 完成预约 - 独立操作，不依赖叫号状态
const handleCompleteAppointment = async (item: QueueItem) => {
  try {
    console.log('完成预约:', item)
    
    const staffId = userStore.userInfo?.staff?.staffId
    if (!staffId) {
      ElMessage.error('获取医生信息失败')
      return
    }

    // 构建请求参数
    const params = {
      id: item.id, // 预约单号id
      staffId: parseInt(staffId), // 转换为数字
      clnicId: item.clnicId,
      slotNo: item.slotNo
    }

    // 发送更新请求
    await appointmentStore.updateAppointmentStatus(params)
    ElMessage.success('预约完成成功')
    
    // 完成后可选择性清除叫号状态（如果正在叫号）
    if (callingStates.value[item.id]) {
      callingStates.value[item.id] = false
      delete callingTimers.value[item.id]
    }
    
    // 刷新叫号队列和预约列表
    await Promise.all([
      handleQueueRefresh(),
      loadAppointmentData()
    ])
    
  } catch (error) {
    console.error('完成预约失败:', error)
    ElMessage.error('完成预约失败')
  }
}

// 手动取消叫号（可选功能）
const handleCancelCall = (appointmentId: string) => {
  callingStates.value[appointmentId] = false
  delete callingTimers.value[appointmentId]
  ElMessage.info('已取消叫号')
}

// 移除原有的组合方法，保持简单的独立操作
// const callQueueItem = ... (删除这个方法)

// 更新callNext方法 - 只负责叫号下一位
const callNext = () => {
  if (appointmentStore.queueList.length > 0) {
    // 找到第一个未叫号的项目进行叫号
    const nextItem = appointmentStore.queueList.find(item => !callingStates.value[item.id])
    if (nextItem) {
      handleCallSlot(nextItem)
    } else {
      // 如果所有人都已叫号，叫第一个
      handleCallSlot(appointmentStore.queueList[0])
    }
  }
}

// 方法
const handleSearch = async () => {
  currentPage.value = 1
  await loadAppointmentData()
}

const handleFilter = async () => {
  currentPage.value = 1
  await nextTick()        // 等待 v-model(filterDate 等) 完成更新
  await loadAppointmentData()
}

const handleSelectionChange = (selection: Appointment[]) => {
  selectedAppointments.value = selection
}

const handleRowClick = (row: Appointment) => {
  appointmentStore.currentAppointment = row
}

const handleViewDetail = (appointment: Appointment) => {
  appointmentStore.currentAppointment = appointment
  showDetailDialog.value = true
}

const handleEdit = (appointment: Appointment) => {
  editingAppointment.value = appointment
  Object.assign(appointmentForm.value, {
    ...appointment,
    appointmentDate: appointment.appointmentDate,
    appointmentTime: appointment.appointmentTime
  })
  showAddDialog.value = true
}

const handleConfirm = async (appointment: Appointment) => {
  try {
    await appointmentStore.confirmAppointment(appointment.id)
    ElMessage.success('确认成功')
  } catch (error) {
    ElMessage.error('确认失败')
  }
}

const handleComplete = async (appointment: Appointment) => {
  try {
    await appointmentStore.completeAppointment(appointment.id)
    ElMessage.success('完成成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleMoreActions = async (command: string, appointment: Appointment) => {
  if (command === 'cancel') {
    try {
      const { value: reason } = await ElMessageBox.prompt(
        '请输入取消原因',
        '取消预约',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '取消原因不能为空'
        }
      )
      
      await appointmentStore.cancelAppointment(appointment.id, reason)
      ElMessage.success('取消成功')
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('取消失败')
      }
    }
  } else if (command === 'noshow') {
    try {
      await appointmentStore.markNoShow(appointment.id)
      ElMessage.success('标记成功')
    } catch (error) {
      ElMessage.error('操作失败')
    }
  } else if (command === 'reminder') {
    try {
      await appointmentStore.sendReminder(appointment.id)
      ElMessage.success('提醒发送成功')
    } catch (error) {
      ElMessage.error('发送失败')
    }
  } else if (command === 'reschedule') {
    handleEdit(appointment)
  }
}

const handlePatientChange = (patientId: string) => {
  const patient = patientOptions.value.find(p => p.id === patientId)
  if (patient) {
    appointmentForm.value.patientName = patient.name
  }
}

const handleDoctorChange = (doctorId: string) => {
  const doctor = doctorOptions.value.find(d => d.id === doctorId)
  if (doctor) {
    appointmentForm.value.doctorName = doctor.name
    appointmentForm.value.department = doctor.department
  }
  // 清空时间选择
  appointmentForm.value.appointmentTime = ''
}

const handleDateChange = () => {
  // 日期变化时清空时间选择
  appointmentForm.value.appointmentTime = ''
}

const handleCalendarChange = () => {
  // 日历月份变化时的处理
}

const getDateAppointments = (date: string) => {
  return appointmentStore.getAppointmentsByDate(date)
}

const disabledDate = (time: Date) => {
  // 禁用过去的日期
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

const handleSave = async () => {
  try {
    await formRef.value.validate()

    const formData = {
      ...appointmentForm.value,
      appointmentDate: appointmentForm.value.appointmentDate,
      appointmentTime: appointmentForm.value.appointmentTime,
      status: '已预约' as Appointment['status'] // 添加默认状态
    }

    if (editingAppointment.value) {
      await appointmentStore.updateAppointment(editingAppointment.value.id, formData)
      ElMessage.success('更新成功')
    } else {
      await appointmentStore.createAppointment(formData)
      ElMessage.success('创建成功')
    }

    showAddDialog.value = false
    resetForm()
    // 刷新数据
    await loadAppointmentData()
  } catch (error) {
    console.error('保存失败:', error)
    if (typeof error === 'string') {
      ElMessage.error(error)
    }
  }
}

const resetForm = () => {
  editingAppointment.value = null
  formRef.value?.resetFields()
  Object.assign(appointmentForm.value, {
    patientId: '',
    patientName: '',
    doctorId: '',
    doctorName: '',
    department: '',
    appointmentDate: '',
    appointmentTime: '',
    type: '初诊',
    reason: '',
    symptoms: '',
    priority: '普通',
    fee: 50,
    paymentStatus: '未支付',
    notes: ''
  })
}

const handleSizeChange = async (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  await loadAppointmentData()
}

const handleCurrentChange = async (page: number) => {
  currentPage.value = page
  await loadAppointmentData()
}

const exportAppointments = () => {
  ElMessage.info('导出功能待开发')
}

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    '已预约': 'primary',
    '排队中': 'success',
    '已完成': 'info',
    '已取消': 'danger',
    '未到诊': 'warning'
  }
  return colorMap[status] || 'info'
}

const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    '初诊': 'primary',
    '复诊': 'success',
    '急诊': 'danger',
    '体检': 'warning'
  }
  return colorMap[type] || 'info'
}

const getPriorityColor = (priority: string) => {
  const colorMap: Record<string, string> = {
    '普通': '',
    '紧急': 'danger',
    '加急': 'warning'
  }
  return colorMap[priority] || ''
}

const getPaymentColor = (status: string) => {
  const colorMap: Record<string, string> = {
    '未支付': 'warning',
    '已支付': 'success',
    '已退款': 'info'
  }
  return colorMap[status] || 'info'
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 新增方法
const formatDisplayTime = (timeStr: string) => {
  if (!timeStr) return '-'
  return timeStr
}

const getStatusText = (status: number | string) => {
  if (typeof status === 'number') {
    return status === 1 ? '已预约' : status === 3 ? '排队中' : '已完成'
  }
  return status
}
const ass = useAppointmentStore()
const handleRefresh = async () => {
  try {
    loading.value = true
    

    
    // 刷新预约数据
    await loadAppointmentData()
    ElMessage.success('刷新成功')
  } catch (error) {
    ElMessage.error('刷新失败')
  } finally {
    loading.value = false
  }
}

// 完善队列刷新方法
const handleQueueRefresh = async () => {
  try {
    // 使用选择的时段，而不是自动判断
    const period = selectedPeriod.value
    const currentClinic = appointmentStore.doctorClinicInfo.find(item => item.period === period)
    
    if (currentClinic && userStore.userInfo?.staff?.staffId) {
      console.log("刷新叫号队列", currentClinic.id, userStore.userInfo.staff.staffId, period)
      try {
        await appointmentStore.getQueueData(userStore.userInfo.staff.staffId, currentClinic.id)
        console.log('叫号队列刷新成功:', appointmentStore.queueList)
        ElMessage.success(`${period}叫号队列刷新成功`)
      } catch (error) {
        console.error('刷新叫号队列失败:', error)
        ElMessage.error(`刷新${period}叫号队列失败`)
      }
    } else {
      ElMessage.warning(`未找到${period}时段的坐诊信息`)
    }
  } catch (error) {
    console.error('刷新队列失败:', error)
  }
}

// 加载预约数据的方法
const loadAppointmentData = async () => {
  try {
    const params: any = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }

    // 优先使用查询表单的数据
    if (queryForm.value.bookedAt) {
      params.bookedAt = `${queryForm.value.bookedAt} 00:00:00`
    } else if (filterDate.value) {
      params.bookedAt = `${filterDate.value} 00:00:00`
    }

    // 参数处理逻辑修改
    if (queryForm.value.period && queryForm.value.period !== '全部' && (queryForm.value.period === '上午' || queryForm.value.period === '下午')) {
      params.period = queryForm.value.period
    } else if (filterPeriod.value && filterPeriod.value !== '全部' && (filterPeriod.value === '上午' || filterPeriod.value === '下午')) {
      params.period = filterPeriod.value
    }
    // 当选择"全部"时，不传递period参数，相当于传null值

    if (queryForm.value.status !== null) {
      params.status = queryForm.value.status
    } else if (filterStatus.value) {
      params.status = parseInt(filterStatus.value)
    }

    if (queryForm.value.patientName) {
      params.patientName = queryForm.value.patientName
    } else if (searchQuery.value) {
      params.patientName = searchQuery.value
    }

    await appointmentStore.getPatientAppointmentsFromAPI(params)
  } catch (error) {
    console.error('加载数据失败:', error)
    throw error
  }
}

// API查询方法
const handleQuery = async () => {
  currentPage.value = 1
  await loadAppointmentData()
}

// 重置查询表单
const handleReset = () => {
  queryForm.value = {
    patientName: '',
    period: '',
    status: null,
    bookedAt: ''
  }
  currentPage.value = 1
  loadAppointmentData()
}

onMounted(async () => {
  try {
    // 初始化默认时段
    initDefaultPeriod()
    
    // 获取当天医生坐诊信息
    const staffId = userStore.userInfo?.staff?.staffId
    if (staffId) {
      try {
        console.log(staffId)
        await appointmentStore.getDoctorClinicInfo(staffId)
        console.log('医生坐诊信息加载成功:', appointmentStore.doctorClinicInfo)
        
        // 坐诊信息加载成功后，立即加载选中时段的叫号队列
        await handleQueueRefresh()
      } catch (error) {
        console.error('获取医生坐诊信息失败:', error)
      }
    }

    // 加载API数据
    await loadAppointmentData()
    // 保持兼容性，也加载其他数据
    await appointmentStore.getAppointments()
    await patientStore.getPatients()
    await doctorStore.getDoctors()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('加载数据失败')
  }
})

// 组件卸载时清理定时器
onUnmounted(() => {
  Object.keys(callingTimers.value).forEach(id => {
    delete callingTimers.value[id]
    delete callingStates.value[id]
  })
})
</script>

<style lang="scss" scoped>
.appointment-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.search-card {
  margin-bottom: 20px;

  .stats-info {
    display: flex;
    align-items: center;
    gap: 20px;

    .stat-item {
      font-size: 14px;
      color: #666;

      strong {
        color: #409EFF;
        margin-left: 4px;
      }
    }
  }
}

.calendar-card {
  margin-bottom: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .calendar-cell {
    height: 80px;
    padding: 4px;

    .date {
      font-weight: bold;
      margin-bottom: 4px;
    }

    .appointments-count {
      font-size: 12px;
    }
  }
}

.normal-priority {
  color: #909399;
  font-size: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.appointment-detail {
  :deep(.el-descriptions__body) {
    background: #fafafa;
  }
}

.list-and-queue {
  align-items: stretch;
}

.queue-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .queue-controls {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
  .queue-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f2f3f5;
    transition: all 0.3s ease;
    
    &.calling {
      background-color: #fff7e6;
      border-left: 3px solid #faad14;
      padding-left: 8px;
      margin-left: -8px;
    }
    
    .left { 
      width: 64px; 
      text-align: center; 
    }
    
    .middle { 
      flex: 1;
      padding: 0 12px;
      
      .calling-status {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .countdown-tag {
          font-weight: bold;
          
          .el-icon {
            margin-right: 4px;
          }
        }
        
        .calling-text {
          color: #faad14;
          font-size: 12px;
          font-weight: bold;
        }
      }
      
      .waiting-status {
        .waiting-text {
          color: #909399;
          font-size: 12px;
        }
      }
    }
    
    .right { 
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
  .current-calling {
    background: #f6ffed;
    border: 1px solid #b7eb8f;
    padding: 12px;
    border-radius: 6px;
    margin-bottom: 12px;
    .calling-info {
      display: flex;
      gap: 8px;
      align-items: center;
      margin-bottom: 8px;
      .name { font-weight: 600; }
      .time { color: #909399; font-size: 12px; }
    }
    .calling-actions {
      display: flex;
      gap: 8px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }

  .search-card {
    :deep(.el-row) {
      .el-col {
        margin-bottom: 12px;
      }
    }
  }

  .calendar-cell {
    height: 60px !important;
    font-size: 12px;
  }
}

.text-gray {
  color: #909399;
  font-style: italic;
}

.query-form {
  .el-form-item {
    margin-bottom: 16px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}
</style>